﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using GPSTrackingWebsiteManager.ClassManager;

namespace GPSTrackingWebsiteManager.Manager.Pages
{
    public partial class MasterRoles_old : System.Web.UI.Page
    {
        private void GetAllMasterRoles()
        {
            MasterRolesGrid.DataSource = GPSTrackingDBV2.Data.DataRepository.MasterRolesProvider.GetAll();
        }

        private GPSTrackingDBV2.Entities.MasterRoles Invoke_EntityMasterRoles(Hashtable Entity)
        {
            GPSTrackingDBV2.Entities.MasterRoles MasterRoleEntity = new GPSTrackingDBV2.Entities.MasterRoles();
            MasterRoleEntity.MasterRoleId = Convert.ToInt32(Entity[GPSTrackingDBV2.Entities.MasterRolesColumn.MasterRoleId.ToString()]);
            MasterRoleEntity.Name = Convert.ToString(Entity[GPSTrackingDBV2.Entities.MasterRolesColumn.Name.ToString()]);

            return MasterRoleEntity;
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                /*GridSortExpression expression = new GridSortExpression();
                expression.FieldName = GPSTrackingDBV2.Entities.MasterRolesColumn.Name.ToString();
                expression.SetSortOrder("Ascending");
                this.MasterRolesGrid.MasterTableView.SortExpressions.AddSortExpression(expression);

                expression = new GridSortExpression();
                expression.FieldName = GPSTrackingDBV2.Entities.MenuItemsColumn.Description.ToString();
                expression.SetSortOrder("Ascending");
                this.MenuItemsGrid.MasterTableView.SortExpressions.AddSortExpression(expression);*/
            }
        }

        protected void MasterRolesGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            GetAllMasterRoles();
            ResizeGrid();
        }

        protected void MasterRolesGrid_InsertCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            try
            {
                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Entities.MasterRoles MasterRoleEntity = Invoke_EntityMasterRoles(Entity);
                MasterRoleEntity.MasterRoleId = GPSTrackingDBV2Custom.Data.DataRepository.MasterRolesProvider.GetNextID();

                GPSTrackingDBV2.Data.DataRepository.MasterRolesProvider.Insert(MasterRoleEntity);
            }
            catch (Exception ex)
            {
                showErrorMessage("No se pudo insertar el rol del master.");
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
            } 


        }

        protected void MasterRolesGrid_UpdateCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            try
            {
                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Entities.MasterRoles MasterRoleEntity = Invoke_EntityMasterRoles(Entity);
                MasterRoleEntity.OriginalMasterRoleId = MasterRoleEntity.MasterRoleId;

                GPSTrackingDBV2.Data.DataRepository.MasterRolesProvider.Update(MasterRoleEntity);
            }
            catch (Exception ex)
            {
                showErrorMessage("No se pudo actualizar el rol del master.");
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
            } 
        }

        protected void MasterRolesGrid_DeleteCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            try
            {
                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Entities.MasterRoles MasterRoleEntity = Invoke_EntityMasterRoles(Entity);                

                GPSTrackingDBV2.Data.DataRepository.MasterRolesProvider.Delete(MasterRoleEntity);
            }
            catch (Exception ex)
            {
                showErrorMessage("No se pudo eliminar el rol del master.");
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
            } 
        }

        protected void MasterRolesGrid_SelectedIndexChanged(object sender, EventArgs e)
        {
            int masterRoleId = getMasterRolesGridValueSelected();
            setSessionManager(masterRoleId);

            GetMenuItemsByMasterRoleId(masterRoleId);
            MenuItemsGrid.DataBind();
            ResizeGrid();
        }

        protected void setSessionManager(int masterRoleId)
        {
            SessionManager objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];
            objSessionManager.MasterRoleID = masterRoleId;
            HttpContext.Current.Session["SessionManager"] = objSessionManager;
        }

        protected int getMasterRolesGridValueSelected()
        {

            try
            {
                foreach (Telerik.Web.UI.GridDataItem selectedItem in MasterRolesGrid.SelectedItems)
                {
                    return int.Parse(selectedItem["MasterRoleId"].Text);
                }
            }
            catch{}
            return -1;
        }

        protected void MenuItemsGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            GetMenuItemsByMasterRoleId(getMasterRolesGridValueSelected());
        }

        private void GetMenuItemsByMasterRoleId(int masterRoleId)
        {
            //GPSTrackingDBV2.Entities.TList<GPSTrackingDBV2.Entities.MasterRolesByMenuItems> MasterRolesByMenuItemsEntity = GPSTrackingDBV2.Data.DataRepository.MasterRolesByMenuItemsProvider.GetByMasterRoleId(masterRoleId);
            //GPSTrackingDBV2.Data.DataRepository.MasterRolesByMenuItemsProvider.DeepLoad(MasterRolesByMenuItemsEntity, true, GPSTrackingDBV2.Data.DeepLoadType.IncludeChildren, typeof(GPSTrackingDBV2.Entities.MenuItems));

            MenuItemsGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.MenuItemsProvider.GetByRoleID(masterRoleId, false, false, true);
        }

        protected void MenuItemsGrid_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            //GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Registro = new Hashtable();
                item.ExtractValues(Registro);

                //tm.BeginTransaction();
                //GPSTrackingDBV2.Entities.MenuItems MenuItemsEntity = Invoke_EntityMenuItems(Registro);

                //GPSTrackingDBV2.Data.DataRepository.MasterRolesByMenuItemsProvider.Delete(getMasterRolesGridValueSelected(), MenuItemsEntity.ItemId);

                //tm.Commit();
            }
            catch (Exception ex)
            {
                //tm.Rollback();
                showErrorMessage("No se pudo quitar la pantalla del rol asociado.");
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
            }
        }

        /*private GPSTrackingDBV2.Entities.MenuItems Invoke_EntityMenuItems(Hashtable Entity)
        {
            GPSTrackingDBV2.Entities.MenuItems MenuItemsEntity = new GPSTrackingDBV2.Entities.MenuItems();
            try
            {
                MenuItemsEntity.ItemId = int.Parse(Entity["ItemID"].ToString());
                MenuItemsEntity.Value = Entity["Value"].ToString();
                if (Entity["ValueOwner"] != null)
                    MenuItemsEntity.ValueOwner = Entity["ValueOwner"].ToString();
                else
                    MenuItemsEntity.ValueOwner = null;
                MenuItemsEntity.Description = Entity["Description"].ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return MenuItemsEntity;
        }*/

        protected void uscMenuItemsSearch_OnCancelEvent()
        {
            ResizeGrid();
        }
        protected void uscMenuItemsSearch_OnAcceptEvent(List<GridDataItem> rows)
        {
            int masterRoleId = getMasterRolesGridValueSelected();

            if (masterRoleId == -1 && rows.Count > 0)
            {
                showWarningMessage("Debe seleccionar un rol para asociar las pantallas.");
            }
            else
            {

                /*foreach (GridDataItem row in rows)
                {
                    GPSTrackingDBV2.Entities.MasterRolesByMenuItems MasterRolesByMenuItemsEntity = new GPSTrackingDBV2.Entities.MasterRolesByMenuItems();
                    MasterRolesByMenuItemsEntity.Dispose();
                    MasterRolesByMenuItemsEntity.MasterRoleId = masterRoleId;
                    MasterRolesByMenuItemsEntity.ItemId = int.Parse(row.Cells[3].Text);

                    GPSTrackingDBV2.Data.DataRepository.MasterRolesByMenuItemsProvider.Insert(MasterRolesByMenuItemsEntity);
                }
                GetMenuItemsByMasterRoleId(masterRoleId);
                MenuItemsGrid.DataBind();*/
            }
            ResizeGrid();
        }

        protected void MasterRolesGrid_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == RadGrid.SortCommandName || e.CommandName == RadGrid.FilterCommandName)
            {
                clearMenuItemsGrid();
                ResizeGrid();
            }
        }

        protected void lbClearMasterRolesFilters_Click(object sender, EventArgs e)
        {
            MasterRolesGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in MasterRolesGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }
            MasterRolesGrid.MasterTableView.Rebind();
            clearMenuItemsGrid();
            ResizeGrid();
        }

        protected void lbClearMenuItemsFilters_Click(object sender, EventArgs e)
        {
            MenuItemsGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in MenuItemsGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }
            MenuItemsGrid.MasterTableView.Rebind();
            ResizeGrid();
        }

        private void ResizeGrid()
        {
            decimal Height = Convert.ToDecimal(HiddenFieldHeight.Value) / 2;

            MasterRolesGrid.Height = Unit.Parse(Convert.ToString(Height));
            MenuItemsGrid.Height = Unit.Parse(Convert.ToString(Height));
        }

        private void clearMenuItemsGrid()
        {
            MenuItemsGrid.DataSource = new string[] { };
            MenuItemsGrid.DataBind();
        }

        protected SessionManager getSessionManager()
        {
            return (SessionManager)HttpContext.Current.Session["SessionManager"];
        }

        protected void lbShowError_Click(object sender, EventArgs e)
        {
            showErrorMessage(HiddenFieldError.Value);
        }

        public void showErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Error", "objWindowsMessageManager.show_Error('" + msg + "','Roles de Administradores...');", true);
        }

        public void showInfoMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Info", "objWindowsMessageManager.show_Info('" + msg + "','Roles de Administradores...');", true);
        }

        public void showWarningMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Warning", "objWindowsMessageManager.show_Warning('" + msg + "','Roles de Administradores...');", true);
        }
    }
}